﻿using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DbToDocument.Core.LiteDB
{
    /// <summary>
    /// LiteDB接口
    /// </summary>
    public interface ILiteDBService
    {
        /// <summary>
        /// 加载所有菜单
        /// </summary>
        /// <returns></returns>
        List<Menu> menus();


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        List<DbConConfig> dbConConfigs();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbConConfig"></param>
        /// <returns></returns>
        DbConConfig Save(DbConConfig dbConConfig);

    }

    /// <summary>
    /// LiteDB服务
    /// </summary>
    public class LiteDBService : ILiteDBService
    {

        /// <summary>
        /// 加载所有
        /// </summary>
        /// <returns></returns>
        public List<Menu> menus()
        {
            using (var db = new LiteDatabase(LiteDBConfig.DBConnectString))
            {
                //获取记录集，没有的话会自动创建
                var lst = db.GetCollection<Menu>(TableName.Menu);
                List<Menu> menus = lst.FindAll().ToList();
                return menus;
            }
        }

        /// <summary>
        ///  加载数据库连接信息
        /// </summary>
        /// <returns></returns>
        public List<DbConConfig> dbConConfigs()
        {
            using (var db = new LiteDatabase(LiteDBConfig.DBConnectString))
            {
                //获取记录集，没有的话会自动创建
                var lst = db.GetCollection<DbConConfig>(TableName.DbConConfig);
                List<DbConConfig> menus = lst.FindAll().ToList();
                return menus;
            }
        }
        /// <summary>
        /// 保存数据库配置
        /// </summary>
        /// <param name="dbConConfig"></param>
        /// <returns></returns>
        public DbConConfig Save(DbConConfig dbConConfig)
        {
            using (var db = new LiteDatabase(LiteDBConfig.DBConnectString))
            {
                var lst = db.GetCollection<DbConConfig>(TableName.DbConConfig);
                if (dbConConfig.Id != null)
                {
                    DbConConfig dbConConfig1 = lst.FindById(dbConConfig.Id);
                    dbConConfig1.ConnectString = dbConConfig.ConnectString;
                    dbConConfig1.Name = dbConConfig.Name;
                    dbConConfig1.DbType = dbConConfig.DbType;
                    lst.Update(dbConConfig1);
                }
                else
                {
                    lst.Insert(dbConConfig);
                }
                return dbConConfig;
            }
        }
    }
}
